import Taro, {Component} from "@tarojs/taro";
import {View, Image, Text, Textarea} from "@tarojs/components";
import {inject, observer} from '@tarojs/mobx'
import {IStoreProps} from '../../store/Stores'
import {getRuntime} from '../../utils/common'
import * as api from "../../api/api";

import './mall.less'
import img_09 from "../../assets/img/img_09.jpg";
import right_white from "../../assets/img/right_white.png";
import address from "../../assets/img/icon_58.png";

// 确认订单
interface IHomeProps extends IStoreProps {
}

@inject("stores")
@observer
class Personnel extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  state = {
    defaultAddress: null, // 用户选择的地址或是默认地址
    itemId: null, // 商品ID
    item: {},
    message: '', // 买家留言
  }

  componentWillMount(): void {
    Taro.setNavigationBarTitle({ title:'确认订单' })
    let itemId = this.$router.params.id
    let userCart = getRuntime().getStorage('userCart')
    console.log(userCart)
    if (itemId && userCart) {
      this.setState({item: userCart})
      /*userCart.map(item => {
        if (parseInt(itemId) === parseInt(item.itemId)) {
          this.setState({item})
        }
      })*/
    }
    this.getUserAddress()
  }

  // 选择地址后更新用户收货地址
  componentDidShow(): void {
    this.getUserAddress()
  }

  handelRouter(url: string = '/pages/index/index'): void {
    getRuntime().navigateTo(url)
  }

  // 获取用户收货地址
  getUserAddress() {
    // 获取用户选择的地址, 然后获取用户默认地址
    let defaultAddress: any = getRuntime().getStorage('userSelectAddress') || null
    // 如果用户没有选择地址，从缓存中获取用户设置的默认地址
    if (defaultAddress) {
      this.setState({
        defaultAddress
      })
    } else {
      // 没有缓存从服务器获取地址
      let {PointMallStore} = this.props.stores
      PointMallStore.getUserDefaultAddress({
        callback: res => {
          defaultAddress = res || null
          this.setState({
            defaultAddress
          })
        }
      })
    }
  }

  inputChange(e) {
    this.setState({message: e.detail.value})
  }

  // 立即付款, 先下单再付款
  placeOrder() {
    let {item, defaultAddress, message} = this.state
    if (!defaultAddress) {
      getRuntime().showToast('请添加收货地址~');
      return
    }
    let {PointMallStore} = this.props.stores
    let itemSpecId = item.specNoId
    let qty = item.itemNum
    let addressId = defaultAddress.id
    PointMallStore.placeOrder({
      form: {
        itemSpecId,
        qty,
        message,
        addressId,
        orderType: 2
      },
      callback: (res) => {
        // 下单成功
        this.pay(res)
      }
    })
  }

  // 支付
  pay(orderInfo: api.YNJWTPointMallVOOrderVO) {
    /* getRuntime().commonPay(orderInfo.id,5,false, () => {
       getRuntime().navigateTo('/pages/mall/pay_success?id='+orderInfo.id)
     })*/
    let {PointMallStore} = this.props.stores
    PointMallStore.pay({
      form: {
        orderId: orderInfo.id,
        payType: 1,
        isPayPoints: false,
      },
      callback: res => {
        // 支付
        //let payParams = JSON.parse(res.payParams)
        getRuntime().wxPay(res, () => {
          getRuntime().navigateTo('/pages/mall/pay_success?id=' + orderInfo.id)
        })
      }
    })
  }

  render() {
    let {defaultAddress, item} = this.state
    let itemNum = item.itemNum
    let itemFreight = item.freight*itemNum
    let itemPrice = item.itemPrice
    let totalMoney = itemPrice + itemFreight
    let publicDonations = (totalMoney * (item.publicDonations / 100)).toFixed(2) // 公益捐款
    return (
      <View className='mall-order-confirm'>
        {defaultAddress &&
        <View className='order-address' onClick={this.handelRouter.bind(this, '/pages/mall/address')}>
           <View className='has-address'>
              <Image className='address-icon' src={address}/>
              <View className='info'>
                 <View className='name'>{defaultAddress.receiver} {defaultAddress.receiverPhone}</View>
                 <View className='address'>{defaultAddress.receiverAddress}</View>
              </View>
              <Image className='drop-down-icon' src={right_white}/>
           </View>
        </View>
        }
        {!defaultAddress &&
        <View className='order-address' onClick={this.handelRouter.bind(this, '/pages/mall/address')}>
           <View className='none-address'>新增收货地址
              <Image className='drop-down-icon' src={right_white}/>
           </View>
        </View>
        }
        <View className='order-spec'>
          <View className='l'>
            <Image className='img' src={img_09}/>
            <View className='info'>
              <View className='list-title'>{item.name}</View>
              <View className='list-info'>
                {/*<Text>5kg</Text>
                <Text className='line'>|</Text>
                <Text>盒装</Text>*/}
                {item.itemSpec}
              </View>
            </View>
          </View>
          <View className='r'>
            <View className='list-price'>
              <Text className='list-small'>￥</Text>{item.itemSignPrice}</View>
            <View className='list-info' style={{textAlign: 'right'}}>
              <Text>x{item.itemNum}</Text>
            </View>
          </View>
        </View>

        <View className='select-spec'>
          <View className='title color'>小计</View>
          <View className='drop-down-con'>
            <Text className='con color'><Text className='list-small'>￥</Text>{itemPrice}</Text>
          </View>
        </View>

        <View className='interval'/>

        <View className='select-spec'>
          <View className='title'>运费</View>
          <View className='drop-down-con'>
            {itemFreight > 0 && <Text className='con'><Text className='list-small'>￥</Text>{itemFreight}</Text>}
            {itemFreight <= 0 && <Text className='con'>免费配送</Text>}
          </View>
        </View>
        <View className='interval'/>

        <View className='from-wrap' style={{padding: 0}}>
          <View className='item-group'>
            <Textarea className='from-textarea' name='message' placeholderClass='placeholder-class'
                      placeholder='请填写备注信息(买家留言)~' style={{padding: 0}}
                      onInput={this.inputChange.bind(this)}

            />
          </View>
        </View>

        {!defaultAddress && <View className='none-address-tip'>
           *请在上方添加收货地址
        </View>}

        <View className='footer-block'/>
        <View className='page-footer2 page-footer3'>
          <View className='all-price'>
            <View className='line'>
              已选 <Text className='color all-count'>{itemNum}</Text> 件商品，合计：
              <Text className='color'><Text className='list-small'>￥</Text>{totalMoney}</Text>
            </View>
            <View className='line gy'>
              公益捐款￥{publicDonations}元
            </View>
          </View>
          <View className='btn-submit' onClick={this.placeOrder.bind(this)}>立即付款</View>
        </View>
      </View>
    )
  }
}

export default Personnel
